package com.yunduo.aspect;

import com.yunduo.common.JwtUtils;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Good;
import com.yunduo.entity.PFile;
import com.yunduo.entity.User;
import com.yunduo.module.FileStore.FileStore;
import com.yunduo.service.GoodService;
import com.yunduo.service.PFileService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 商品切面
 */
@Aspect
@Component
@Slf4j
public class GoodAspect {

    @Resource
    private GoodService goodService;

    @Resource
    private FileStore fileStore;

    @Resource
    private PFileService pFileService;

    //删除商品的切面
    @Pointcut(value = "execution(* com.yunduo.controller.GoodController.deletesGood(..))")
    public void deletePoint(){}

    //切面删除商品剩余数据
    @Before(value = "GoodAspect.deletePoint()")
    public void loginUserTotal(JoinPoint point) {
        Object arg0 = point.getArgs()[0];
        String[] ids = (String[])arg0;
        Thread deleteGoodsAsset = new Thread(()->{
            List<Good> list = (List<Good>) goodService.listByIds(Arrays.asList(ids));
            Iterator<Good> iterator = list.iterator();
            while (iterator.hasNext()){
                Good next = iterator.next();
                //删除封面
                PFile file = pFileService.getFileByUrl(next.getCover());
                fileStore.deleteFile(YunDuoUtils.getFileObjForPFile(file));
                pFileService.removeById(file.getId());
                //删除效果图
                if(next.getDetilImg()!=null && next.getDetilImg().length() > 0){
                    String[] imgs = next.getDetilImg().split("_");
                    List<PFile> pFiles = (List<PFile>) pFileService.listByIds(Arrays.asList(imgs));
                    pFiles.forEach(item -> {
                        fileStore.deleteFile(YunDuoUtils.getFileObjForPFile(item));
                        pFileService.removeById(item.getId());
                    });
                }
            }
        });
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        StringBuilder goods = new StringBuilder();
        for(int i = 0; i < ids.length; i++){
            goods.append(ids[i]+" ");
        }
        log.info(user.getName() + " " + "删除商品:"+goods+" 附带资源");
        deleteGoodsAsset.start();
    }
}
